import javafx.util.Pair;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-20
 * Time: 22:27
 */
class Solution5 {
    public List<String> topKFrequent(String[] words, int k) {
        // 1.创建哈希表，统计频数
        Map<String,Integer> hash = new HashMap<>();

        // 2.放元素
        for(String s : words) {
            hash.put(s,hash.getOrDefault(s,0)+1);
        }

        // 3.创建堆
        PriorityQueue<Pair<String,Integer>> heap = new PriorityQueue<>(
                (a,b)-> {
                    if(a.getValue().equals(b.getValue())) {
                        // 频率相同，按字典序排
                        return b.getKey().compareTo(a.getKey());
                    }
                    return a.getValue()-b.getValue();
                }
        );

        // 4.TopK
        for(Map.Entry<String,Integer> e : hash.entrySet()) {
            heap.offer(new Pair<>(e.getKey(),e.getValue()));
            if(heap.size() > k) {
                heap.poll();
            }
        }

        // 5.提取结果
        List<String> ret = new ArrayList<>();

        while(!heap.isEmpty()) {
            ret.add(heap.poll().getKey());
        }

        Collections.reverse(ret);
        return ret;
    }
}
